package com.ruoyi.redis.controller;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.util.auth.PhoneAuth;

import cn.hutool.core.util.RandomUtil;

/**
 * @Description: 使用redis,实现验证吗功能 
 * @ClassName: RedisAndAuthCode
 * @author syc
 * @date: 2022年6月7日 下午6:01:19
 */
@RestController
@RequestMapping(value = "captcha", method = RequestMethod.POST)
public class RedisAndAuthCode {
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	/**
	 * @Description: 获取手机验证码
	 * @author syc
	 * @date: 2022年6月7日 下午6:46:50
	 */
	@RequestMapping("getauthcode")
	public JSONObject getPhoneAuthCode(@RequestBody JSONObject requestJson) {
		JSONObject returnJson = new JSONObject();
		String phone = requestJson.getString("phone");
		if (!PhoneAuth.isChinaMobile(phone)) {
			returnJson.put("error", "手机号验证错误请重新填写!");
			return returnJson;
		}
		/**
		 * 获取验证码
		 */
		String code = RandomUtil.randomString(6);
		stringRedisTemplate.opsForValue().set("authcode:" + phone, code, 180, TimeUnit.SECONDS);
		// 发送短信 (忽略)
		System.out.println(code);
		returnJson.put("code", code);		
		return returnJson;
	}
	
	/**
	 * @Description: 获取手机验证码
	 * @author syc
	 * @date: 2022年6月7日 下午6:46:50
	 */
	@RequestMapping("login")
	public JSONObject login (@RequestBody JSONObject requestJson) {
		JSONObject returnJson = new JSONObject();
		String phone = requestJson.getString("phone");
		if (!PhoneAuth.isChinaMobile(phone)) {
			returnJson.put("error", "手机号验证错误请重新填写!");
			return returnJson;
		}
		String code = requestJson.getString("code");
      	String authcode = 	stringRedisTemplate.opsForValue().get("authcode:" + phone);
       if (StringUtils.isBlank(authcode)) {
    	   returnJson.put("error", "验证码已经过期");
			return returnJson;
       }
      	
       if(!code.equals(authcode)) {
    	   returnJson.put("error", "验证码错误请重新填写");
			return returnJson;
       }
        // 生成 tocken 将tocken存入redis,并返回前端 
		returnJson.put("status", "success");	
		// 删除 key
		stringRedisTemplate.delete("authcode:" + phone);
		return returnJson;
	}


	
	
	
	
}
